package com.caiheng.api.controller.platform;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.util.*;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *@Author: ZhouWei
 *@Description:  通知公告类 相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/wxmini")//url:模块/资源/{}/细分
public class WxMiniController extends BaseController {

    @Value("${web.appid}")
    private String appid;
    @Value("${web.secret}")
    private String secret;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private WxTemplateService wxTemplateService;
    /**
     *  重新获取配置信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getSign")
    public JSONObject getSign(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "wxmini/getSign 接收的参数： "+requestParam);
            System.out.println("orderAppraise/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String paramUrl = jsonRequest.containsKey("url") ? jsonRequest.getStr("url") : null;

//            String access_token = redisTemplate.opsForValue().get("access_token")!=null ? redisTemplate.opsForValue().get("access_token").toString() : null;
//            if(StrUtil.isEmpty(access_token)){
//                access_token = WxMessage.getACCESSTOKEN(appid,secret);
//                redisTemplate.opsForValue().set("access_token",access_token,3600L, TimeUnit.SECONDS);
//            }
            String access_token = wxTemplateService.getAccessToken(1);// WxMessage.getACCESSTOKEN(appid,secret);

            String jsapi_ticket = redisTemplate.opsForValue().get("jsapi_ticket")!=null ?redisTemplate.opsForValue().get("jsapi_ticket").toString():null;
            if(StrUtil.isEmpty(jsapi_ticket)){
                String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
                Response response = OkHttpClientUtil.getInstance().getData(url);
                if(response.code() == 200){
                    String ret = response.body().string();
                    JSONObject jsonObject = JSONUtil.parseObj(ret);
                    if(jsonObject!=null){
                        jsapi_ticket = jsonObject.getStr("ticket");
                        redisTemplate.opsForValue().set("jsapi_ticket",jsapi_ticket,3600L, TimeUnit.SECONDS);
                    }
                }
            }
            map = WxSign.sign(jsapi_ticket,paramUrl);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  重新获取配置信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUrlScheme")
    public JSONObject getUrlScheme(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "wxmini/getSign 接收的参数： "+requestParam);
            System.out.println("orderAppraise/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String paramUrl = jsonRequest.containsKey("url") ? jsonRequest.getStr("url") : null;

//            String access_token = redisTemplate.opsForValue().get("access_token")!=null ? redisTemplate.opsForValue().get("access_token").toString() : null;
//            if(StrUtil.isEmpty(access_token)){
//                access_token = WxMessage.getACCESSTOKEN(appid,secret);
//                redisTemplate.opsForValue().set("access_token",access_token,3600L, TimeUnit.SECONDS);
//            }
            String access_token = WxMessage.getACCESSTOKEN(appid,secret);
//            redisTemplate.opsForValue().set("access_token",access_token,7200L, TimeUnit.SECONDS);


            String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token="+access_token;
            // 发送请求参数
            JSONObject innerParamJson = new JSONObject();
            innerParamJson.set("path","/pages/personal/index");
            innerParamJson.set("query","id=1");
            JSONObject paramJson = new JSONObject();
            paramJson.set("jump_wxa",innerParamJson);
            paramJson.set("is_expire",false);


            String response = OkHttpClientUtil.getInstance().postJson(url,JSONUtil.toJsonStr(paramJson));
//            System.out.println("response: "+ response);
//            if(response.code() == 200){
//                String ret = response.body().string();
//                System.out.println("ret: "+ ret);
//                JSONObject jsonObject = JSONUtil.parseObj(ret);
//                if(jsonObject!=null){
//
//                }
//            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",JSONUtil.parse(response)),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


}
